<script setup>
import { ref } from 'vue'
import { updateCate, insertCate, plusCate } from '@/api/cate'

const dialogVisible = ref(false)
const imageURL = ref()
const formModel = ref({
  id: '',
  name: '',
})
const pId = ref()
const open = async (row,pid) => {
  formModel.value = {}
  imageURL.value = ''
  pId.value = ''
  dialogVisible.value = true
  if (row !== null) {
    formModel.value = { ...row }
    imageURL.value = row.image
  }
  if (pid) {
    pId.value = pid
  }
  
}

const formRef = ref()
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()

  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }

  if (pId.value === null) {
    formModel.value.id
    ? await updateCate(fd)
    : await insertCate( fd )
  } else {
    await plusCate (fd,pId.value)
  }
  
  ElMessage({
    type: 'success',
    message: formModel.value.id ? '编辑成功' : '添加成功'
  })
  dialogVisible.value = false
  formModel.value = {}
  imageURL.value = ''
  emit('success')
}
defineExpose({
  open
})

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    // {
    //   pattern: /^\S{1,10}$/,
    //   message: '分类名必须是1-10位的非空字符',
    //   trigger: 'blur'
    // }
  ]
}
const onUploadFile = (uploadFile) => {
  imageURL.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.image = uploadFile.raw
}

</script>
<template>
  <el-dialog
    :title="formModel.id ? '编辑分类' : '添加分类'"
    ref="dialog"
    v-model="dialogVisible"
    width="500"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formModel.name"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品封面" prop="image">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imageURL" :src="imageURL" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
